package Servlet;


import bean.Message;
import dao.MessageDao;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(name = "chat_Content", value = "/chat_Content")
public class chatContent extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");

        String id = request.getParameter("id");
        String toID = request.getParameter("toId");
        String content = request.getParameter("content");
        String type = request.getParameter("type");

        MessageDao message = new MessageDao();
        Message mes = new Message(toID,id);
        mes.setContent(content);
        mes.setType(type);
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        BigDecimal now = new BigDecimal(df.format(new Date()));
        mes.setSendTime(now.toBigInteger().longValue());
        boolean flag = message.sendMessage(mes);
        HttpSession session = request.getSession();
        session.setAttribute("newMessage",mes);

        PrintWriter out = response.getWriter();
        Map map =new HashMap();
        if(flag){
            List<Message> messages = message.listAllPersonalMassage(id,toID);
            out.print(JSONArray.fromObject(messages));
        }else{
            map.put("isR","false");
            out.print(JSONObject.fromObject(map));
        }



    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }


}
